package it.tempogara.tgsender;

import it.tempogara.tgsender.R;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Date;
import java.util.HashMap;
import java.util.StringTokenizer;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.commons.net.ftp.FTPClient;

public class MainActivity extends Activity {

	String readerAddr;
	String content;
	String type;
	String sendAddress;
	String tagsFile;
	File fTemp;
	TextView logText;
	MyThreadSender th;
	Button bStop;
	ToneGenerator tg;
	ApplicationData appData;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		logText = (TextView) findViewById(R.id.textViewLog);
		appData = (ApplicationData)getApplication();
		final ListView lv = (ListView) findViewById(R.id.listView1);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		String[] values = prefs.getString("IP", "192.168.10.20").split(","); 
		lv.setAdapter(new ArrayAdapter<String>(this, R.layout.row, values));
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
//				TextView txt = (String) lv.getItemAtPosition(arg2);//(TextView) findViewById(R.id.rowTextView);
				appData.ipReader = (String) lv.getItemAtPosition(arg2);//txt.getText().toString().trim();
//				appData.ipReader = (String) arg0.getItemAtPosition(arg2);//(String) (lv.getItemAtPosition(arg2));
				Button b = (Button) findViewById(R.id.button1);
				b.setEnabled(true);
			}
			
		});
		try {
			tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, ToneGenerator.MAX_VOLUME);
		    tg.startTone(ToneGenerator.TONE_PROP_PROMPT);
		    Thread.sleep(500);
		    tg.startTone(ToneGenerator.TONE_PROP_PROMPT);
		    Thread.sleep(500);
		    tg.startTone(ToneGenerator.TONE_PROP_PROMPT);
		} catch (InterruptedException e) {
				e.printStackTrace();
		}
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void sendLast(View v) throws Exception{
		bStop.setEnabled(true);
		if(th!=null)
			if(!th.isCancelled())
				th.cancel(true);
		th = new MyThreadSender(this);
		th.multiple=false;
		th.execute();
	}
	
	public void sendLastN(View v) throws Exception{
		bStop.setEnabled(true);
		if(th!=null)
			if(!th.isCancelled())
				th.cancel(true);
		th = new MyThreadSender(this);
		th.multiple=true;
		th.execute();
	}
	
	public void downloadLast(View v){
		logText.setText("");
		MyThreadSender th = new MyThreadSender(this);
		RadioButton bS = (RadioButton) findViewById(R.id.radioSingle);
		RadioButton bM = (RadioButton) findViewById(R.id.radioMultiple);
		if(bS.isChecked())
			th.multiple=false;
		else
			th.multiple=true;
		th.download=true;
		th.execute();	
		Button b = (Button) findViewById(R.id.button2);
		b.setEnabled(true);
	}
	
	public void sendLastFile(View v){
//		logText.setText("Ricorda di disconnetterti dal lettore e connetterti ad una rete internet");
//		Toast.makeText(this, "Ricorda di disconnetterti dal lettore e connetterti ad una rete internet", Toast.LENGTH_SHORT).show();
		MyThreadSender th = new MyThreadSender(this);
		RadioButton bS = (RadioButton) findViewById(R.id.radioSingle);
		RadioButton bM = (RadioButton) findViewById(R.id.radioMultiple);
		if(bS.isChecked())
			th.multiple=false;
		else if(appData.tagsFile.length>1)
			th.multiple=true;
		th.download=false;
		th.send=true;
		th.execute();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		if(requestCode==1){
			final ListView lv = (ListView) findViewById(R.id.listView1);
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			String[] values = prefs.getString("IP", ",192.168.10.20").split(","); 
			lv.setAdapter(new ArrayAdapter<String>(this, R.layout.row, values));
		}
	}
	
	public void settings(View v){
		Intent i = new Intent(this,SettingsActivity.class);
		startActivityForResult(i,1);
	}
	
	public void sfoglia(View v){
		Intent i = new Intent(this,BrowseActivity.class);
		startActivityForResult(i,2);
	}
	
	public void stop(View v){
		bStop.setEnabled(false);
		th.stop=true;
		logText.append("Downlaod terminato dall'utente \n");
	}
	
	private String download(String address) {
		String output;
		OutputStream out;
		InputStream in;
		output = null;
		out = null;
		in = null;
		try {
			logText.setText("Connessione al reader in corso");
			URL url = new URL(address);
			out = new ByteArrayOutputStream();
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(2000);
			conn.setReadTimeout(2000);
			in = conn.getInputStream();
			byte buffer[] = new byte[1024];
			int numRead;
			while ((numRead = in.read(buffer)) != -1)
				out.write(buffer, 0, numRead);
			output = out.toString();
			System.out.println((new StringBuilder("Scaricato:")).append(output).toString());
			logText.setText((new StringBuilder("Scaricato:")).append(output).toString());
		} catch (Exception exception) {
			logText.setText("Errore di connessione");
		} finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
			} catch (IOException ioexception) {
			}
		}
		return output;
	}

}
